package jaux.tank.generator.template;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Resource;
import org.beetl.core.Template;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.StringTemplateResourceLoader;

import jaux.tank.generator.util.CollectionUtil;
import jaux.tank.generator.util.AppUtil;
import jaux.tank.generator.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TankTemplate {

	public static final String TANK_TEMPLATE_ROOT = "templates/";
	
	private static TankTemplate instance = null;

	private   GroupTemplate groupTemplate;
	private GroupTemplate stringTemplate;
	
	private TankTemplate() throws IOException   {
		try (ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(TANK_TEMPLATE_ROOT)) {
			Configuration cfg = Configuration.defaultConfiguration();
			groupTemplate = new GroupTemplate(resourceLoader, cfg);
			stringTemplate = new GroupTemplate(new StringTemplateResourceLoader(), cfg);
			registerFunctions();
		}
	}


	private void registerFunctions() {
		stringTemplate.registerFunctionPackageAsRoot(StringUtil.class);
		groupTemplate.registerFunctionPackageAsRoot(StringUtil.class);
		stringTemplate.registerFunctionPackageAsRoot(CollectionUtil.class);
		groupTemplate.registerFunctionPackageAsRoot(CollectionUtil.class);
		stringTemplate.registerFunctionPackage("appUtil", AppUtil.class);
		groupTemplate.registerFunctionPackage("appUtil", AppUtil.class);
	}
	
	
	public static TankTemplate getInstance() throws IOException   {
		if(instance == null 
				|| instance.groupTemplate ==null
				|| instance.stringTemplate == null) {
			instance = new TankTemplate();
		}
		return instance;
	}
	
	public Template getTemplate(String templateName) {
		Template template = groupTemplate.getTemplate(templateName);
		BeetlException templateException = template.validate();
		if(templateException != null) {
			log.error("validate template error", templateException);
			return null;
		}
		return template;
	}
	public Template getStringTemplate(String templateString) {
		Template template = stringTemplate.getTemplate(templateString);
		BeetlException templateException = template.validate();
		if(templateException != null) {
			log.error("validate template error", templateException);
			return null;
		}
		return template;
	}
	
	public void render(String templateName, Object root, OutputStream output)   {
		Template t = getTemplate(templateName);
		t.binding("_root", root);
		t.renderTo( output);
	}
	public String renderString(String templateString, Object root)   {
		Template t = getStringTemplate(templateString);
		t.binding("_root", root);
		return t.render();
	}
}
